package com.BigDate.server.service.impl;

import com.BigDate.server.mapper.ExperimentMapper;
import com.BigDate.server.mapper.ForkExpMapper;
import com.BigDate.server.mapper.UserMapper;
import com.BigDate.server.pojo.*;
import com.BigDate.server.service.IExperimentService;
import com.BigDate.server.utils.MarkDownUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.BigDate.server.utils.pyUtils;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stx
 * @since 2021-12-26
 */
@Service
public class ExperimentServiceImpl extends ServiceImpl<ExperimentMapper, Experiment> implements IExperimentService {

    @Autowired
    private ExperimentMapper experimentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ForkExpMapper forkExpMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 获取实验(分页)
     * @param currentPage
     * @param size
     * @param experiment
     * @return
     */
    @Override
    public RespPageBean getExpByPage(Integer currentPage, Integer size, Experiment experiment) {
        Page<Experiment> page = new Page<>(currentPage,size);
        IPage<Experiment> experimentIPage = experimentMapper.getExpByPage(page,experiment);
        RespPageBean respPageBean = new RespPageBean(experimentIPage.getTotal(),experimentIPage.getRecords());
        return respPageBean;
    }

    /**
     * 获取内容
     * @param id
     * @return
     */
    @Override
    public String getContent(Integer id) {
        Experiment experiment = experimentMapper.selectById(id);
        return MarkDownUtils.openFile(experiment.getContent());

    }

    @Override
    public List<Experiment> findLimitPr() {
        return experimentMapper.findLimitPr();
    }

    @Override
    public List<Experiment> findLimitIt() {
        return experimentMapper.findLimitIt();
    }

    @Override
    public List<Experiment> findLimitHi() {
        return experimentMapper.findLimitHi();
    }

    @Override
    public Experiment findById(Integer id) {
        return experimentMapper.findById(id);
    }

    @Override
    public RespBean runPython(Integer expId, Integer userId) {
        String port = redisTemplate.opsForValue().get("port");
        if(pyUtils.checkPort(port) == true){
            return RespBean.error("你有项目正在运行，请先保存并停止该项目");
        }else if(pyUtils.checkPort(port) == false){
            Experiment experiment = experimentMapper.selectById(expId);
            User user = userMapper.selectById(userId);
            user.setPassword(null);
            long time = System.currentTimeMillis();
            String defPath = "C:\\Users\\11920\\.jupyter\\";
            String userDir = expId+user.getUsername()+time;
            File userWork = new File(defPath+userDir);
            userWork.mkdir();
            try {
                MarkDownUtils.downIpynb(null,experiment.getContent(),defPath+userDir+"\\");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String cmd = "jupyter lab --port "+port+" --notebook-dir "+defPath+userDir;
            System.out.println("运行的指令"+cmd);
            String cmd3 = "cmd /k notedown "+defPath+userDir+"\\2.md > "+defPath+userDir+"\\1.ipynb";
            try {
                Process p = Runtime.getRuntime().exec(cmd);
                Process p2 = Runtime.getRuntime().exec(cmd3);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 运行成功 添加fork记录
            ForkExp forkExp = new ForkExp();
            forkExp.setExpid(expId);
            forkExp.setUserid(userId);
            forkExp.setForktime(new Date());
            forkExp.setNickname(user.getNickname());
            System.out.println("添加的记录:"+forkExp);
            forkExpMapper.insert(forkExp);
            return RespBean.success("正在进入Python界面",userDir);
        }
        return RespBean.error("未知错误发生");
    }

    /**
     * 通过id获取实验
     * @param id
     * @return
     */
    @Override
    public List<Experiment> getExpByUserId(Integer id) {
        return experimentMapper.selectList(new QueryWrapper<Experiment>().eq("userid",id));
    }



}
